package com.neusoft.a132wxyorderingdish.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.neusoft.a132wxyorderingdish.R;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;

public class PhotoActivity extends BaseActivity implements View.OnClickListener {
    private Button natives,pai,submit;
    private ImageView img;
    private ImageButton photo_return;
    private EditText img_content;
    private TextView textView15;
    String TAG="PhotoActivity";
    private static String srcPath="";
    LinearLayout photo_full;
    private static final int TIME_OUT=10*100;//超时时间
    private static final String CHARSET="utf-8";//设置编码

    @Override
    void initViews() {
        setLayout_file(R.layout.activity_photo);
        natives=findViewById(R.id.natives);
        pai=findViewById(R.id.pai);
        submit=findViewById(R.id.submit);
        photo_return=findViewById(R.id.photo_back);
        img_content=findViewById(R.id.img_content);
        textView15=findViewById(R.id.textView15);
        photo_full=findViewById(R.id.photo_full);
        img=findViewById(R.id.img);
    }

    @Override
    void initEvents() {
        natives.setOnClickListener(this);
        pai.setOnClickListener(this);
        submit.setOnClickListener(this);
        photo_return.setOnClickListener(this);
        View.OnClickListener keyboard_hide=new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                InputMethodManager imm=(InputMethodManager)PhotoActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(),0);
            }
        };
        photo_full.setClickable(true);
        photo_full.setOnClickListener(keyboard_hide);
    }

    @Override
    void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.natives:
                Intent local;
                local = new Intent();
                local.setType("image/*");
                local.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(local,2);
                break;
            case R.id.pai:
                Intent it=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(it,1);
                break;
            case R.id.submit:
                if(srcPath==null||srcPath==""){
                    Toast.makeText(this, "文件不存在", Toast.LENGTH_SHORT).show();
                }
                else {
                    Intent intent=new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putString("srcPath",srcPath);
                    intent.putExtras(bundle);
                    setResult(1,intent);
                    finish();
                }
                break;

            case R.id.photo_back:
                Intent intent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("srcPath","");
                intent.putExtras(bundle);
                setResult(1,intent);
                finish();
                break;
        }
    }
    //拍照上传
    protected  void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 1:
                    Bundle extras = data.getExtras();
                    Bitmap b = (Bitmap) extras.get("data");
                    img.setImageBitmap(b);
                    String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                    String fileName = Environment.getExternalStorageDirectory().toString() + File.separator + "dong/image/" + name + ".jpg";
                    srcPath = fileName;
                    System.out.println(srcPath + "----------保存路径1");
                    File myCaptureFile = new File(fileName);
                    try {
                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                            if (!myCaptureFile.getParentFile().exists()) {
                                myCaptureFile.getParentFile().mkdirs();
                            }
                            BufferedOutputStream bos;
                            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                            b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();
                        } else {
                            Toast toast = Toast.makeText(PhotoActivity.this, "保存失败,SD卡失效", Toast.LENGTH_SHORT);
                            toast.setGravity(Gravity.CENTER, 0, 0);
                            toast.show();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    Uri uri = data.getData();
                    img.setImageURI(uri);
                    ContentResolver cr = this.getContentResolver();
                    Cursor c = cr.query(uri, null, null, null, null);
                    c.moveToFirst();
                    //这是获取图片保存在sdcrad中的位置i
                    srcPath = c.getString(c.getColumnIndex("_data"));
                    System.out.println(srcPath + "----------保存路径2");
                    break;
                default:
                    break;
            }
            ;
        }
    }
    private void submitUploadFile(){
        final  File file=new File(srcPath);
        if(file==null||(!file.exists())){
            return;
        }
        Log.i(TAG,"请求的fileName="+file.getName());
        final Map<String,String> params=new HashMap<String,String>();
        params.put("user_id",getUser_id());
        params.put("file_type","");
        params.put("content",img_content.getText().toString());
        new Thread(new Runnable() {
            @Override
            public void run() {
                uploadFile(file,"",params);
            }
        }).start();
    }
    private String uploadFile(File file,String RequestURL,Map<String,String>param){
        String result=null;
        String BOUNDARY= UUID.randomUUID().toString();
        String PREFIX="--",LINE_END="\r\n";
        String CONTENT_TYPE="multipart/form-data";
        try {
            URL url=new URL(RequestURL);
            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
            conn.setReadTimeout(TIME_OUT);
            conn.setConnectTimeout(TIME_OUT);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Charset",CHARSET);
            conn.setRequestProperty("connection","keep-alive");
            conn.setRequestProperty("Content-Type",CONTENT_TYPE+";boundary="+BOUNDARY);
            if(file!=null){
                DataOutputStream dos=new DataOutputStream(conn.getOutputStream());
                StringBuffer sb=new StringBuffer();
                String params="";
                if(param!=null&&param.size()>0){
                    Iterator<String> it=param.keySet().iterator();
                    while(it.hasNext()){
                        sb=null;
                        sb=new StringBuffer();
                        String key=it.next();
                        String value=param.get(key);
                        sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
                        sb.append("Content-Disposition:form-data;name\"").append(key).append("\"").append(LINE_END).append(LINE_END);
                        sb.append(value).append(LINE_END);
                        params=sb.toString();
                        Log.i(TAG,key+"="+params+"##");
                        dos.write(params.getBytes());
                    }
                }
                sb=new StringBuffer();
                sb.append(PREFIX);
                sb.append(BOUNDARY);
                sb.append(LINE_END);
                sb.append("Content-Disposition:form-data;name=\"upfile\";filename=\""+file.getName()+"\""+LINE_END);
                sb.append("Content-Type:imagepeg;charset="+CHARSET+LINE_END);
                sb.append(LINE_END);
                dos.write(sb.toString().getBytes());
                InputStream is=new FileInputStream(file);
                byte[] bytes=new byte[1024];
                int len=0;
                while((len=is.read(bytes))!=-1){
                    dos.write(bytes,0,len);
                }
                is.close();
                dos.write(LINE_END.getBytes());
                byte[] end_data=(PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
                dos.write(end_data);
                dos.flush();

                int res=conn.getResponseCode();
                System.out.println("res====="+res);
                if(res==200){
                    InputStream input=conn.getInputStream();
                    StringBuffer sb1=new StringBuffer();
                    int ss;
                    while ((ss=input.read())!=-1){
                        sb1.append((char)ss);
                    }
                    result=sb1.toString();
                    finish();
                }
                else {

                }
            }
        }catch (MalformedURLException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        return result;
    }

}
